package com.iyimo.loader
{
	import com.iyimo.event.LoadEvent;
	
	import flash.events.EventDispatcher;

	[Event(name="LOAD_ALL_COMPLETE", type="com.iyimo.event.LoadEvent")]
	
	public class MutilLoader extends EventDispatcher{
		/**
		 * 下载数据来源,为 name:url的key value或者
		 * 为自身的list(作为loader set来用)
		 */		
		public var source:Array;
		
		protected var loader:BaseLoader;
		
		/**
		 * 当前加载的个数
		 */		
		protected var _index:int = 0;
		
		public function MutilLoader(){
			loader = new BaseLoader();
			loader.addEventListener(LoadEvent.COMPLETE, onComplete);
		}
		
		/**
		 * 开始加载资源,如果之前提供过source,参数value可以为null
		 */		
		public function load(value:Array = null):void{
			if (value != null)
				source = value;
			if (source == null)
				throw new Error("source must be NOT NULL");
		}
		
		protected function onComplete(e:LoadEvent):void{
			_index++;
			if (_index == source.length)
				loadFinish();
			else
				load();
		}
		
		protected function loadFinish():void{
			var e:LoadEvent = new LoadEvent(LoadEvent.ALL_COMPLETE);
			dispatchEvent(e);
			
			clear();
		}
		
		protected function clear():void{
			if (loader)
				loader.removeEventListener(LoadEvent.COMPLETE, onComplete);
			loader = null;
			source = null;
		}
	}
}